/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.rbac.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.star.framework.rbac.entity.User;
import cn.star.framework.rbac.entity.UserRole;
import cn.star.framework.rbac.repository.UserRepository;
import cn.star.framework.rbac.repository.UserRoleRepository;
import cn.star.framework.rbac.service.IRbacUserService;
import cn.star.framework.rbac.service.PasswordEncoderService;
import cn.star.framework.rbac.service.UserService;
import cn.star.framework.service.AbstractService;
import cn.star.framework.type.Status;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * {@link IRbacUserService}<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class UserServiceImpl extends AbstractService<User, String, UserRepository>
    implements UserService {
  @Autowired private UserRoleRepository userRoleRepository;
  @Autowired private PasswordEncoderService passwordEncoderService;

  public UserServiceImpl(UserRepository repository) {
    super(repository);
  }

  @Override
  public User findByUsername(String username) {
    return repository.findByUsernameEquals(username);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lock(User user) {
    user.setAccountNonLocked(false);
    
    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unlock(User user) {
    user.setAccountNonLocked(true);
    user.setPasswordErrorTimes(0);
    
    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void enable(User user) {
    user.setEnabled(true);
    user.setStatus(Status.ENABLED);
    
    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void disable(User user) {
    user.setEnabled(false);
    user.setStatus(Status.DISABLE);
    
    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void passwordRest(String id, String password) {
    User user = this.findById(id);
    user.setPassword(passwordEncoderService.encode(password));
    user.setPasswordModifyTime(new Date());

    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void passwordModify(String id, String newPassword, String oldPassword) {
    User user = this.findById(id);
    Assert.isFalse(newPassword.equals(oldPassword), "The old and new passwords cannot be the same");
    Assert.isTrue(
        passwordEncoderService.matches(oldPassword, user.getPassword()),
        "The old password is incorrect");
    user.setPassword(passwordEncoderService.encode(newPassword));
    user.setPasswordModifyTime(new Date());

    repository.save(user);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public List<User> deleteByIds(Iterable<String> ids) {
    List<User> list = repository.findAllById(ids);
    // 删除用户角色关系
    List<UserRole> userRoles = userRoleRepository.findByUserIdIn(CollectionUtil.newArrayList(ids));
    userRoleRepository.deleteAllInBatch(userRoles);
    // 删除用户
    repository.deleteAllInBatch(list);

    return list;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void delete(Iterable<User> entities) {
    List<String> ids = new ArrayList<>();
    if (CollectionUtil.isNotEmpty(entities)) {
      for (User user : entities) {
        ids.add(user.getId());
      }
    }

    this.deleteByIds(ids);
  }
}
